package com.cheng.example.atguigu.view2.client31;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 可重入读写锁测试
 *
 * 1、写锁安装创建顺序进行排序
 * 2、写锁使用或者排队状态，读锁暂时不能使用（也就是代码不能执行）
 */
public class Client31 {
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    private volatile Map<String, Object> map = new HashMap<>();

    public void put(String key, Object value) {
        rwLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() + "\t 正在写入：" + key);
            try {
                map.put(key, value);
                TimeUnit.MICROSECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t 写入完成：");
        }finally {
            rwLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        rwLock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() + "\t 正在读取：");
            //暂停一会儿线程
            try {
                TimeUnit.MICROSECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Object result = map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t 读取完成："+result);
        }finally {
            rwLock.readLock().unlock();
        }
    }

    public static void main(String[] args) {

        Client31 client31 = new Client31();

        //
        for (int i = 0; i < 5; i++) {
            final int y = i;
            new Thread(()->{
                client31.put(" "+y,new Object());
            },"t"+i).start();
        }

        for (int i = 0; i < 5; i++) {
            final int y = i;
            new Thread(()->{
                client31.get(" "+y);
            },"t"+i).start();
        }

    }
}
